import datetime
import json
import logging
import os
import sys

import requests
from flask import Blueprint, jsonify

# 添加项目根目录到 Python 路径
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

# 修复导入问题，使用项目中的DB类而不是config模块中的DB函数
from DB.DB import DB

from app.modules1.PublicApproach import get_token_result
from app.modules1.common.encryptionUtils import getResult2

# 设置标准输出编码为UTF-8，确保中文正确显示
if sys.stdout.encoding != 'utf-8':
    sys.stdout.reconfigure(encoding='utf-8')

# 数据库连接函数

# 创建蓝图
vendinfo_bp = Blueprint('Supply_chain_data', __name__)

# 创建日志目录
log_dir = os.path.join(os.path.dirname(__file__), "logs")
os.makedirs(log_dir, exist_ok=True)

# 使用标准日志配置
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(os.path.join(log_dir, "Supply_chain_data.log"), encoding='utf-8'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)


def get_Supply_chain_data(date_range=None):
    url = "https://env3.jkyservice.com/jkyun/udr/report/reportDesign/showdata"
    token = get_token_result()
    headers = {
        "authority": "env3.jkyservice.com",
        "method": "POST",
        "path": "/jkyun/erp/vendinfo/payaccountcreate",
        "scheme": "https",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "zh-CN,zh;q=0.9",
        "module_code": "supplier_list_new_list",
        "origin": "https://env3.jkyservice.com",
        "priority": "u=1, i",
        "authorization": token,
    }

    # 如果没有提供日期范围，则使用默认日期
    if date_range is None:
        start_date_str = "2025-09-01 00:00:00"
        end_date_str = datetime.date.today().strftime("%Y-%m-%d 23:59:59")
        date_range = f"{start_date_str},{end_date_str}"

    filterKeyValueJson = json.dumps([
        {"key": "货品编号", "value": ""},
        {"key": "货品名称", "value": ""},
        {"key": "是否独家", "value": ""},
        {"key": "品类负责人", "value": ""},
        {"key": "产品负责人", "value": ""},
        {"key": "货品分类", "value": ""},
        {"key": "time", "value": "consign_time"},
        {"key": "inout_date_key", "value": date_range}
    ])

    data = {
        "chartLevel": 1,
        "chartType": "table",
        "chartSubType": "table",
        # "chartTheme": '{"lineSpecificTheme":{},"sheetTheme":"custom","miscellaneous":{"classNlightame":"-content","isDataLablePosition":"top","isDataLableRotate":"","isMaximumPart":"0","isDifferentColors":"0","yAxisMax":null,"yAxisMin":null,"yAxisInterval":null,"secondyAxisMax":null,"secondyAxisMin":null,"secondyAxisInterval":null,"wordSize":"","isXaxisLabeUnitPart":"","isYaxisLabeUnitPart":"","isSecondYaxisLabeUnitPart":"","xNameLocation":"end","yNameLocation":"end","secondaryYNameLocation":"end","xNameRotate":"","yNameRotate":"","secondaryYNameRotate":"","pageIconColor":" #aaa","pageIconInactiveColor":"#2f4554","dataLabel":"{c}","otherPie":"","indicatorAlignPart":"left","indicatorMainNamePart":"1","indicatorAssistantNamePart":"1","indicatorTypefaceN":"#ffffff","indicatorWordSizeN":"","indicatorThicknessN":"","indicatorTypefaceN2":"#ffffff","indicatorWordSizeN2":"","indicatorThicknessN2":"","indicatorTypefaceV":"#ffffff","indicatorWordSizeV":"","indicatorThicknessV":"","indicatorTypefaceV2":"#ffffff","indicatorWordSizeV2":"","indicatorThicknessV2":"","guidelines":"","secondGuidelines":"","guidelinesValue":0,"secondGuidelinesValue":0,"listHeaderColor":"#ffffff","listHeaderSize":"","listBodyColor":"#ffffff","listBodySize":"","topStylePart":"top-style4","percentCalcType":"1","funnelSort":"","isColorWidthSeries":"0","isAlternating":"0"},"componentsFontColor":"#333333","componentsBkColor":"#ffffff","componentsColorStyle":"walden","isLegendEnable":"0","mapSpecificTheme":{},"componentsOpacity":"100","isDataLableEnable":"0","sheetBackgroundImage":"theme-background4","axisSpecificTheme":{},"chartType":"table","chartSubType":"table","componentsTheme":"custom"}',
        # "componentsName": "自定义图表2297358648940693632",
        "datasetId": "2297357770317891712",
        # "totalDatasetId": "",
        "chartProperties": '{"columnX":[],"columnY":[],"columnY2":[]}',
        "columnDisplayProperties": '[{"columnName":"time"},{"columnName":"inout_date_key"},{"columnName":"货品编号"},{"columnName":"货品名称"},{"columnName":"货品分类"},{"columnName":"单品成本"},{"columnName":"标准成本价"},{"columnName":"销量"},{"columnName":"总销售收入"},{"columnName":"电商销售收入"},{"columnName":"门店销售收入"},{"columnName":"其他销售收入"},{"columnName":"标记"},{"columnName":"品类负责人"},{"columnName":"产品负责人"},{"columnName":"是否独家"},{"columnName":"毛利额"},{"columnName":"毛利率"},{"columnName":"25年度总销售额"},{"columnName":"24年度总销售额"}]',
        "columnDisplayPropertiesDetail": '[{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"0","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2124,"isSum":"1","mappingIdentifyField":"","_uid":2124,"numericScale":"2","exportFormat":"0","columnName":"总销售收入"},{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"0","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2125,"isSum":"1","mappingIdentifyField":"","_uid":2125,"numericScale":"2","exportFormat":"0","columnName":"电商销售收入"},{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"0","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2126,"isSum":"1","mappingIdentifyField":"","_uid":2126,"numericScale":"2","exportFormat":"0","columnName":"门店销售收入"},{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"0","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2127,"isSum":"1","mappingIdentifyField":"","_uid":2127,"numericScale":"2","exportFormat":"0","columnName":"其他销售收入"},{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"0","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2128,"isSum":"1","mappingIdentifyField":"","_uid":2128,"numericScale":"2","exportFormat":"0","columnName":"毛利额"},{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"0","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2129,"isSum":"1","mappingIdentifyField":"","_uid":2129,"numericScale":"2","exportFormat":"0","columnName":"25年度总销售额"},{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"0","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2130,"isSum":"1","mappingIdentifyField":"","_uid":2130,"numericScale":"2","exportFormat":"0","columnName":"24年度总销售额"},{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"3","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2131,"isSum":"0","mappingIdentifyField":"","_uid":2131,"numericScale":"2","exportFormat":"0","columnName":"毛利率"},{"isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isCellMerge":"0","jkselected":false,"isThousandSeparator":"0","isFieldPermissions":"0","dataAlignment":"center","fieldNameCn":"","isDisplay":"0","isSumTotal":"0","decryptMapField":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","nullEmpty":"0","_id":2132,"isSum":"1","mappingIdentifyField":"","_uid":2132,"numericScale":"0","exportFormat":"0","columnName":"销量"},{"fieldNameCn":"","isPercent":"0","isFilterControlled":"0","fieldStyleOverride":"0","memo":"","isDisplay":"0","isCellMerge":"0","isSumTotal":"0","decryptMap极":"","isDecryption":"0","_state":"added","permissionsFieldGroup":"","permissionsFieldName":"","isThousandSeparator":"0","isFieldPermissions":"0","nullEmpty":"0","_id":2134,"is极":"0","dataAlignment":"center","mappingIdentifyField":"","_uid":2134,"numericScale":"2","exportFormat":"0","columnName":"标准成本价"}]',
        "columnDisplayPropertiesSpecial": '[{"flagIconColor":"#000000","backgroundColor":"#f44336","rangeType":"0","rangeFieldIcon":"","isIcon":"0","textColor":"#000000","visitName":"单品成本异常","_state":"added","flagBg极":"#f44336","visitConditionType":"0","rangeField":"","dataList":[{"field":"单品成本","selection":"标准成本价","_state":"added","_id":2015,"_uid":2015,"operator":">","_jkHasChanged":True,"undefined":"="}],"_id":3813,"_uid":3813,"isText":"1","flagFontColor":"#000000","signIcon":"none"},{"flagIconColor":"#000000","backgroundColor":"#f44336","rangeType":"0","rangeFieldIcon":"","isIcon":"0","text极":"#000000","visitName":"毛利率小于1%","_state":"added","flagBgColor":"#f44336","visitConditionType":"0","rangeField":"","dataList":[{"field":"毛利率","_state":"added","_id":3815,"_uid":3815,"value":"-0.01","operator":"<","_jkHasChanged":True,"_jkIsSetData":True,"undefined":"0"}],"_id":3814,"_uid":3814,"isText":"极","flagFontColor":"#000000","signIcon":"none"}]',
        # "uniqueDataId": "",
        "ySortConfig": '{"ySortField":"","ySort":""}',
        "chartPrivatePropertyConfig": '{"isZoom":0,"topN":20,"progressField":"","fixedValue":"100","targetValue":"","fixedMinValue":"0","targetMinValue":"","fixedMaxValue":"100","targetMax极":"","numReserve":null,"numReserveSecond":null,"fieldSelectPercentage":"","dataFormat":"","fieldSelectPercentageSecond":"","dataFormatSecond":"","fieldsYType":"contrastBar","fieldsY2Type":"contrastLine"}',
        "filterJson": [
            {
                "cockpitPosition": "in",
                "cueWord": "",
                "dataType": "date",
                "filterType": 4,
                "hideFilter": 0,
                "isMandatory": 1,
                "limitTimeRange": 0,
                "limitTimeType": "",
                "paramDefault": "近七日",
                "paramId": 2305796448751617500,
                "paramName": "inout_date_key",
                "paramNameCn": "时间选择",
                "popupWidth": "100%",
                "reportId": 2297358648940693500
            },
            {
                "cockpitPosition": "in",
                "cueWord": "",
                "dataType": "batchQuery",
                "filterType": 12,
                "hideFilter": 0,
                "isMandatory": 0,
                "limitTimeRange": 0,
                "limitTimeType": "",
                "paramDefault": "",
                "paramId": 2305796448751617500,
                "paramName": "货品编号",
                "paramNameCn": "货品编号",
                "popupWidth": "极",
                "reportId": 2297358648940693500
            },
            {
                "cockpitPosition": "in",
                "cueWord": "",
                "dataType": "charFuzzyQuery",
                "filterType": 1,
                "hideFilter": 0,
                "isMandatory": 0,
                "limitTimeRange": 0,
                "极TimeType": "",
                "paramDefault": "",
                "paramId": 2305796448751617500,
                "paramName": "货品名称",
                "paramNameCn": "货品名称",
                "popupWidth": "100%",
                "reportId": 2297358648940693500
            },
            {
                "cockpitPosition": "in",
                "cueWord": "",
                "dataType": "enum",
                "enumValue": [
                    {
                        "_id": 2627,
                        "_uid": 2627,
                        "_state": "added",
                        "text": "是",
                        "_jkHasChanged": True,
                        "value": "是"
                    },
                    {
                        "_id": 2628,
                        "_uid": 2628,
                        "_state": "added",
                        "text": "否",
                        "_jkHasChanged": True,
                        "value": "否"
                    }
                ],
                "filterType": 2,
                "hideFilter": 0,
                "isMandatory": 0,
                "limitTimeRange": 0,
                "limitTimeType": "",
                "paramDefault": "",
                "paramId": 2305796448751617500,
                "paramName": "是否独家",
                "paramNameCn": "是否独家",
                "popupWidth": "100%",
                "reportId": 2297358648940693500
            },
            {
                "cockpitPosition": "in",
                "cueWord": "",
                "dataType": "enum",
                "enumValue": [
                    {
                        "_id": 2263,
                        "_uid": 2263,
                        "_state": "added",
                        "text": "柏玉",
                        "_jkHasChanged": True,
                        "undefined": "柏玉",
                        "value": "柏玉"
                    },
                    {
                        "_id": 2264,
                        "_uid": 2264,
                        "_state": "added",
                        "text": "买祖拉",
                        "_jkHasChanged": True,
                        "undefined": "买祖拉",
                        "value": "买祖拉"
                    },
                    {
                        "_id": 2265,
                        "_uid": 2265,
                        "_state": "added",
                        "text": "莫弱男",
                        "_jkHasChanged": True,
                        "undefined": "莫弱男",
                        "value": "莫弱男"
                    },
                    {
                        "_id": 2266,
                        "_uid": 2266,
                        "_state": "added",
                        "text": "王雪",
                        "_jkHasChanged": True,
                        "undefined": "王雪",
                        "value": "王雪"
                    }
                ],
                "filterType": 3,
                "hideFilter": 0,
                "isMandatory": 0,
                "limitTimeRange": 0,
                "limitTimeType": "",
                "paramDefault": "",
                "paramId": 2305796448751617500,
                "paramName": "品类负责人",
                "paramNameCn": "品类负责人",
                "popupWidth": "100%",
                "report极": 2297358648940693500
            },
            {
                "cockpitPosition": "in",
                "cueWord": "",
                "dataType": "enum",
                "enumValue": [
                    {
                        "_id": 2269,
                        "_uid": 2269,
                        "_state": "added",
                        "text": "柏玉",
                        "_极HasChanged": True,
                        "undefined": "柏玉",
                        "value": "柏玉"
                    },
                    {
                        "_id": 2270,
                        "_uid": 2270,
                        "_state": "added",
                        "text": "马永春",
                        "_jkHasChanged": True,
                        "undefined": "马永春",
                        "value": "马永春"
                    },
                    {
                        "_id": 2271,
                        "_uid": 2271,
                        "_state": "added",
                        "text": "买祖拉",
                        "_jkHasChanged": True,
                        "undefined": "买祖拉",
                        "value": "买祖拉"
                    },
                    {
                        "_id": 2272,
                        "_uid": 2272,
                        "_state": "added",
                        "text": "莫弱男",
                        "_jkHasChanged": True,
                        "undefined": "莫弱男",
                        "value": "莫弱男"
                    },
                    {
                        "_id": 2273,
                        "_uid": 2273,
                        "_state": "added",
                        "text": "王雪",
                        "_jkHasChanged": True,
                        "undefined": "王雪",
                        "value": "王雪"
                    }
                ],
                "filterType": 3,
                "hideFilter": 0,
                "isMandatory": 0,
                "limitTimeRange": 0,
                "limitTimeType": "",
                "paramDefault": "",
                "paramId": 2305796448751617500,
                "paramName": "产品负责人",
                "paramNameCn": "产品负责人",
                "popupWidth": "100%",
                "reportId": 2297358648940693500
            },
            {
                "cockpitPosition": "in",
                "cueWord": "",
                "dataType": "enum",
                "enumValue": [
                    {
                        "_id": 2283,
                        "_uid": 2283,
                        "_state": "added",
                        "text": "LLM",
                        "_jkHasChanged": True,
                        "undefined": "LLM",
                        "value": "LLM"
                    },
                    {
                        "_id": 2284,
                        "_uid": 2284,
                        "_state": "added",
                        "text": "百货",
                        "_jkHasChanged": True,
                        "undefined": "百货",
                        "value": "百货"
                    },
                    {
                        "_id": 2285,
                        "_uid": 2285,
                        "_state": "added",
                        "text": "端午产品",
                        "_jkHasChanged": True,
                        "undefined": "端午产品",
                        "value": "端午产品"
                    },
                    {
                        "_id": 2286,
                        "_uid": 2286,
                        "_state": "added",
                        "text": "妆品/文创/纺织",
                        "_jkHasChanged": True,
                        "undefined": "妆品/极/纺织",
                        "value": "妆品/极/纺织"
                    },
                    {
                        "_id": 2287,
                        "_uid": 2287,
                        "_state": "added",
                        "text": "中秋产品",
                        "_jkHasChanged": True,
                        "undefined": "中秋产品",
                        "value": "中秋产品"
                    },
                    {
                        "_id": 2288,
                        "_uid": 2288,
                        "_state": "added",
                        "text": "原料",
                        "_jkHasChanged": True,
                        "undefined": "原料",
                        "value": "原料"
                    },
                    {
                        "_id": 2289,
                        "_uid": 2289,
                        "_state": "added",
                        "text": "香烟",
                        "_jkHasChanged": True,
                        "undefined": "香烟",
                        "value": "香烟"
                    },
                    {
                        "_id": 2290,
                        "_uid": 2290,
                        "_state": "added",
                        "text": "西域奇珍",
                        "_jkHasChanged": True,
                        "undefined": "西域奇珍",
                        "value": "西域奇珍"
                    },
                    {
                        "_id": 2291,
                        "_uid": 2291,
                        "_state": "added",
                        "text": "水果/蔬菜",
                        "_jkHasChanged": True,
                        "undefined": "水果/蔬菜",
                        "极lue": "水果/蔬菜"
                    },
                    {
                        "_id": 2292,
                        "_uid": 2292,
                        "_state": "added",
                        "text": "社区团购",
                        "_jkHasChanged": True,
                        "undefined": "社区团购",
                        "value": "社区团购"
                    },
                    {
                        "_id": 2293,
                        "_uid": 2293,
                        "_state": "added",
                        "text": "乳制品",
                        "_jkHasChanged": True,
                        "undefined": "乳制品",
                        "value": "乳制品"
                    },
                    {
                        "_id": 2294,
                        "_uid": 2294,
                        "_state": "added",
                        "text": "肉制品",
                        "_jkHasChanged": True,
                        "undefined": "肉制品",
                        "value": "肉制品"
                    },
                    {
                        "_id": 2295,
                        "_uid": 2295,
                        "_state": "added",
                        "text": "零食/速食",
                        "_jkHasChanged": True,
                        "undefined": "零食/速食",
                        "value": "零食/速食"
                    },
                    {
                        "_id": 2296,
                        "_uid": 2296,
                        "_state": "added",
                        "text": "粮油副食",
                        "_jkHasChanged": True,
                        "undefined": "粮油副食",
                        "value": "粮油副食"
                    },
                    {
                        "_id": 2297,
                        "_uid": 2297,
                        "_state": "added",
                        "text": "冷冻速食",
                        "_jkHasChanged": True,
                        "undefined": "冷冻速食",
                        "value": "冷冻速食"
                    },
                    {
                        "_id": 2298,
                        "_uid": 2298,
                        "_state": "added",
                        "text": "酒水/饮料",
                        "_jkHasChanged": True,
                        "undefined": "酒水/饮料",
                        "value": "酒水/饮料"
                    },
                    {
                        "_id": 2299,
                        "_uid": 2299,
                        "_state": "added",
                        "text": "糕点",
                        "_jkHasChanged": True,
                        "undefined": "糕点",
                        "value": "糕点"
                    },
                    {
                        "_id": 2300,
                        "_uid": 2300,
                        "_极tate": "added",
                        "text": "干果/炒货",
                        "_jkHasChanged": True,
                        "undefined": "干果/炒货",
                        "value": "干果/炒货"
                    },
                    {
                        "_id": 2301,
                        "_uid": 2301,
                        "_state": "added",
                        "text": "茶/大健康",
                        "_jkHasChanged": True,
                        "undefined": "茶/大健康",
                        "value": "茶/大健康"
                    }
                ],
                "filterType": 3,
                "hideFilter": 0,
                "isMandatory": 0,
                "limitTimeRange": 0,
                "limitTimeType": "",
                "paramDefault": "",
                "paramId": 2305796448751617500,
                "paramName": "货品分类",
                "paramNameCn": "货品分类",
                "popupWidth": "100%",
                "reportId": 2297358648940693500
            },
            {
                "cockpitPosition": "in",
                "cueWord": "",
                "dataType": "enum",
                "enumValue": [
                    {
                        "_id": 1971,
                        "_uid": 1971,
                        "_state": "added",
                        "text": "发货时间",
                        "_jkHasChanged": True,
                        "value": "consign_time",
                        "undefined": "consgin_time"
                    },
                    {
                        "_id": 1972,
                        "_uid": 1972,
                        "_state": "added",
                        "text": "下单时间",
                        "_jkHasChanged": True,
                        "value": "trade_time"
                    }
                ],
                "filterType": 2,
                "hide极lter": 0,
                "isMandatory": 1,
                "极mitTimeRange": 0,
                "limitTimeType": "",
                "paramDefault": "consign_time",
                "paramId": 2305796448751617500,
                "paramName": "time",
                "paramNameCn": "时间维度",
                "popupWidth": "100%",
                "reportId": 2297358648940693500
            }
        ],
        "filterKeyValueJson": filterKeyValueJson,
        "reportId": "2297358648940693632",
        "pageIndex": 0,
        "pageSize": 1000,
        "cols": '["time", "inout_date_key", "货品编号", "货品名称", "货品分类", "单品成本", "标准成本价", "销量", "总销售收入", "电商销售收入", "门店销售收入", "其他销售收入", "标记", "品类负责人", "产品负责人", "是否独家", "毛利额", "毛利率", "25年度总销售额", "24年度总销售额"]'
    }

    data['filterJson'] = json.dumps(data['filterJson'], ensure_ascii=False, indent=2)

    # print(data)

    requests_data = getResult2(token, data)
    # print('requests_data1111111111111111111', requests_data)
    resp = requests.post(url, headers=headers, data=requests_data)
    # print("===============", resp.json())
    return resp


def extract_Supply_chain_data(api_response):
    """
    从供应链接口返回的数据中提取需要的信息

    Args:
        api_response (dict): 接口返回的完整JSON数据

    Returns:
        list: 提取后的数据列表
    """
    # 检查请求是否成功
    if api_response.get('code') == 200 and api_response.get('msg') == '操作成功':
        # 提取数据部分
        data_list = api_response.get('result', {}).get('data', {}).get('data', [])

        extracted_data = []
        for item in data_list:
            # 提取需要的字段
            extracted_item = {
                '货品编号': item.get('货品编号'),
                '货品名称': item.get('货品名称'),
                '货品分类': item.get('货品分类'),
                '单品成本': item.get('单品成本'),
                '标准成本价': item.get('标准成本价'),
                '销量': item.get('销量'),
                '总销售收入': item.get('总销售收入'),
                '电商销售收入': item.get('电商销售收入'),
                '门店销售收入': item.get('门店销售收入'),
                '其他销售收入': item.get('其他销售收入'),
                '标记': item.get('标记'),
                '品类负责人': item.get('品类负责人'),
                '产品负责人': item.get('产品负责人'),
                '是否独家': item.get('是否独家'),
                '毛利额': item.get('毛利额'),
                '毛利率': item.get('毛利率'),
                '25年度总销售额': item.get('25年度总销售额'),
                '24年度总销售额': item.get('24年度总销售额')
            }
            extracted_data.append(extracted_item)
        return extracted_data
    else:
        print(f"接口调用失败: {api_response.get('msg')}")
        return []


def save_data_to_database(data_list, record_date):
    """
    将数据保存到数据库

    Args:
        data_list (list): 提取的数据列表
        record_date (str): 记录日期，格式为 'YYYY-MM-DD'
    """
    connection = DB()  # 现在使用的是DB类而不是DB函数
    try:
        with connection.conn.cursor() as cursor:  # 注意这里使用了connection.conn
            # 直接插入数据，使用record_date作为区分每天数据的字段
            insert_sql = """
            INSERT INTO c_supply_chain_daily_data (
                record_date, product_code, product_name, product_category, 
                unit_cost, standard_cost, sales_volume, total_sales_revenue,
                ecommerce_sales_revenue, store_sales_revenue, other_sales_revenue,
                tags, category_manager, product_manager, is_exclusive,
                gross_profit, gross_profit_margin, sales_25_year, sales_24_year
            ) VALUES (
                %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s
            )
            """

            inserted_count = 0
            for item in data_list:
                try:
                    cursor.execute(insert_sql, (
                        record_date,
                        item.get('货品编号'),
                        item.get('货品名称'),
                        item.get('货品分类'),
                        item.get('单品成本') or None,
                        item.get('标准成本价') or None,
                        item.get('销量') or None,
                        item.get('总销售收入') or None,
                        item.get('电商销售收入') or None,
                        item.get('门店销售收入') or None,
                        item.get('其他销售收入') or None,
                        item.get('标记'),
                        item.get('品类负责人'),
                        item.get('产品负责人'),
                        item.get('是否独家'),
                        item.get('毛利额') or None,
                        item.get('毛利率') or None,
                        item.get('25年度总销售额') or None,
                        item.get('24年度总销售额') or None
                    ))
                    inserted_count += 1
                except Exception as item_error:
                    # 检查是否是重复键错误
                    if "Duplicate entry" in str(item_error):
                        print(f"数据已存在，跳过插入 (日期: {record_date}, 产品: {item.get('货品编号')})")
                    else:
                        print(f"插入数据时发生错误 (产品: {item.get('货品编号')}): {item_error}")
                    # 继续处理下一条数据

            print(f"成功插入 {inserted_count} 条新数据")

        connection.conn.commit()  # 注意这里使用了connection.conn.commit()
        print(f"日期 {record_date} 的数据已成功保存到数据库")

    except Exception as e:
        print(f"保存数据时发生错误: {e}")
        connection.conn.rollback()  # 注意这里使用了connection.conn.rollback()
    finally:
        # 不再需要手动关闭连接，因为DB类的__del__方法会处理
        pass


def fetch_and_save_daily_data():
    """
    获取并保存每日数据（9月1日到今天）
    """
    # 设置日期范围：从9月1日到今天
    start_date = datetime.date(2025, 9, 1)
    end_date = datetime.date.today()  # 今天

    current_date = start_date
    while current_date <= end_date:
        try:
            # 设置查询日期范围为当天
            start_date_str = current_date.strftime("%Y-%m-%d 00:00:00")
            end_date_str = current_date.strftime("%Y-%m-%d 23:59:59")
            date_range = f"{start_date_str},{end_date_str}"

            # 调用API获取数据
            print(f"正在获取 {current_date} 的数据...")
            response = get_Supply_chain_data(date_range)
            extracted_data = extract_Supply_chain_data(response.json())

            # 保存数据到数据库
            save_data_to_database(extracted_data, current_date.strftime("%Y-%m-%d"))

            print(f"已处理 {current_date} 的数据")
        except Exception as e:
            print(f"处理 {current_date} 的数据时发生错误: {e}")

        current_date += datetime.timedelta(days=1)

    print("所有日期的数据处理完成")


def fetch_and_save_specific_date_data(target_date):
    """
    获取并保存指定日期的数据
    
    Args:
        target_date (datetime.date): 要同步数据的日期
    """
    try:
        # 设置查询日期范围为当天
        start_date_str = target_date.strftime("%Y-%m-%d 00:00:00")
        end_date_str = target_date.strftime("%Y-%m-%d 23:59:59")
        date_range = f"{start_date_str},{end_date_str}"

        # 调用API获取数据
        print(f"正在获取 {target_date} 的数据...")
        response = get_Supply_chain_data(date_range)
        extracted_data = extract_Supply_chain_data(response.json())

        # 保存数据到数据库
        save_data_to_database(extracted_data, target_date.strftime("%Y-%m-%d"))

        print(f"已处理 {target_date} 的数据，共 {len(extracted_data)} 条记录")
        return True
    except Exception as e:
        print(f"处理 {target_date} 的数据时发生错误: {e}")
        return False


@vendinfo_bp.route('/api/sync_previous_day_data', methods=['POST'])
def sync_previous_day_data_api():
    """
    API接口：同步前一天的供应链数据
    """
    try:
        # 计算前一天的日期
        previous_day = datetime.date.today() - datetime.timedelta(days=1)
        previous_day_str = previous_day.strftime("%Y-%m-%d")

        # 检查前一天的数据是否已存在
        from app.moudules9.supply_chain_scheduler import check_data_exists
        if check_data_exists(previous_day_str):
            logger.info(f"{previous_day_str} 的供应链数据已存在，跳过同步")
            return jsonify({
                "code": 200,
                "msg": "数据已存在，无需重复同步",
                "data": {
                    "date": previous_day_str,
                    "exists": True
                }
            })

        start_date_str = previous_day.strftime("%Y-%m-%d 00:00:00")
        end_date_str = previous_day.strftime("%Y-%m-%d 23:59:59")
        date_range = f"{start_date_str},{end_date_str}"

        logger.info(f"开始同步 {previous_day} 的供应链数据")

        # 获取数据
        response = get_Supply_chain_data(date_range)
        extracted_data = extract_Supply_chain_data(response.json())

        # 保存数据
        save_data_to_database(extracted_data, previous_day.strftime("%Y-%m-%d"))

        logger.info(f"成功同步 {previous_day} 的供应链数据，共处理 {len(extracted_data)} 条记录")

        return jsonify({
            "code": 200,
            "msg": "数据同步成功",
            "data": {
                "date": previous_day.strftime("%Y-%m-%d"),
                "count": len(extracted_data)
            }
        })
    except Exception as e:
        logger.error(f"同步前一天供应链数据时发生错误: {e}")
        return jsonify({
            "code": 500,
            "msg": f"数据同步失败: {str(e)}"
        }), 500


if __name__ == '__main__':
    # 手动同步特定日期的数据 (例如2025年9月23日)
    target_date = datetime.date(2025, 9, 27)
    fetch_and_save_specific_date_data(target_date)

    # 或者同步9月1日到今天的所有数据
    # fetch_and_save_daily_data()
